#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：Employment_class 
@File    ：13_单进程服务器-select.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/6/006 10:13 
"""

import select
import sys
from socket import *

serSocket = socket(AF_INET, SOCK_STREAM)
serSocket.bind(("", 7789))
serSocket.listen(5)

inputs = [serSocket, sys.stdin]

running = True

while True:
    # 调用select函数，堵塞等待
    readable, writeable, exceptional = select.select(inputs, [], [])
    for sock in readable:
        if sock == serSocket:
            clientSocket,clientAddr = serSocket.accept()
            inputs.append(clientSocket)
        elif sock == sys.stdin:
            cmd = sys.stdin.readline()
            running = False
            break
        else:
            data = sock.recv(1024)
            if data:
                sock.send(data)
            else:
                inputs.remove(sock)
                sock.close()

    if not running:
        break

serSocket.close()